<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/axios'

// 搜索表单
const searchForm = ref({
  name: '',
  type: null
});

// 数据列表
const drugList = ref([]);
// 加载状态
const loading = ref(false);
// 对话框显示状态
const dialogVisible = ref(false);
const dialogTitle = ref('新增药品');

// 表单对象
const drugForm = ref({
  id: null,
  name: '',
  type: null,
  price: null,
  number: null,
  text: ''
});

// 表单规则
const rules = {
  name: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择药品类型', trigger: 'change' }],
  price: [{ required: true, message: '请输入单价', trigger: 'blur' }],
  number: [{ required: true, message: '请输入数量', trigger: 'blur' }]
};

// 药品类型选项
const typeOptions = [
  { value: 1, label: '处方药' },
  { value: 2, label: '非处方药' },
  { value: 3, label: '中药' }
];

// 表单引用
const formRef = ref(null);

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    type: null
  };
  loadDrugList();
};

// 加载药品列表
const loadDrugList = async () => {
  loading.value = true;
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.error('请先登录');
    loading.value = false;
    return;
  }

  try {
    const { data: res } = await axios.get("/drugs/list", {
      params: searchForm.value,
      headers: {
        'Authorization': token
      }
    });
    if (res.code === 200) {
      drugList.value = res.data;
    } else {
      ElMessage.error(res.message || '查询失败');
    }
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录');
    } else {
      ElMessage.error('查询失败：' + error.message);
    }
  } finally {
    loading.value = false;
  }
};

// 打开新增对话框
const handleAdd = () => {
  dialogTitle.value = '新增药品';
  drugForm.value = {
    id: null,
    name: '',
    type: null,
    price: null,
    number: null,
    text: ''
  };
  dialogVisible.value = true;
};

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑药品';
  drugForm.value = { ...row };
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.error('请先登录');
    return;
  }

  try {
    await formRef.value.validate();
    
    const url = drugForm.value.id ? '/drugs/update' : '/drugs/add';
    
    const { data: res } = await axios.post(url, drugForm.value, {
      headers: {
        'Authorization': token,
        'Content-Type': 'application/json'
      }
    });
    
    if (res.code === 200) {
      ElMessage.success(drugForm.value.id ? '更新成功' : '新增成功');
      dialogVisible.value = false;
      loadDrugList();
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录');
    } else {
      ElMessage.error('操作失败：' + error.message);
    }
  }
};

// 删除药品
const handleDelete = async (id) => {
  if (!id) {
    ElMessage.error('无效的药品ID');
    return;
  }

  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.error('请先登录');
    return;
  }

  try {
    await ElMessageBox.confirm('确认删除该药品吗？', '提示', {
      type: 'warning'
    });
    
    const { data: res } = await axios.post(`/drugs/del/${id}`, null, {
      headers: {
        'Authorization': token
      }
    });
    if (res.code === 200) {
      ElMessage.success('删除成功');
      loadDrugList();
    } else {
      ElMessage.error(res.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message);
    }
  }
};

// 关闭对话框
const handleClose = () => {
  ElMessageBox.confirm('确认关闭？未保存的数据将会丢失', '提示', {
    type: 'warning'
  }).then(() => {
    dialogVisible.value = false;
    drugForm.value = {};
  }).catch(() => {});
};

onMounted(() => {
  loadDrugList();
});
</script>

<template>
  <div style="background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">药品管理</span>
  </div>

  <!-- 搜索卡片 -->
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="药品名称">
        <el-input 
          placeholder="请输入" 
          style="width:220px;" 
          v-model="searchForm.name"
          @keydown.enter="loadDrugList"
        ></el-input>
      </el-form-item>
      <el-form-item label="药品类型">
        <el-select 
          v-model="searchForm.type" 
          placeholder="请选择"
          style="width:220px;"
        >
          <el-option label="全部" :value="null"></el-option>
          <el-option 
            v-for="item in typeOptions" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadDrugList">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="success" @click="handleAdd">新增药品</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 药品列表 -->
  <el-card style="margin:20px;">
    <el-table 
      :data="drugList" 
      v-loading="loading"
      border 
      stripe 
      style="width: 100%"
    >
      <el-table-column prop="name" label="药品名称" width="180"></el-table-column>
      <el-table-column prop="type" label="药品类型" width="120">
        <template #default="scope">
          {{ typeOptions.find(item => item.value === scope.row.type)?.label || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="单价" width="120">
        <template #default="scope">
          ￥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="number" label="数量" width="120"></el-table-column>
      <el-table-column prop="text" label="介绍" width="650"></el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDelete(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 新增/编辑对话框 -->
  <el-dialog 
    :title="dialogTitle" 
    v-model="dialogVisible" 
    width="50%"
    :before-close="handleClose"
  >
    <el-form 
      ref="formRef"
      :model="drugForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="药品名称" prop="name">
        <el-input 
          v-model="drugForm.name" 
          placeholder="请输入药品名称"
          maxlength="50"
        ></el-input>
      </el-form-item>

      <el-form-item label="药品类型" prop="type">
        <el-select 
          v-model="drugForm.type" 
          placeholder="请选择药品类型"
          style="width: 100%"
        >
          <el-option 
            v-for="item in typeOptions" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="单价" prop="price">
            <el-input-number
              v-model="drugForm.price"
              :precision="2"
              :step="0.1"
              :min="0"
              style="width: 100%"
              placeholder="请输入单价"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数量" prop="number">
            <el-input-number
              v-model="drugForm.number"
              :min="0"
              :precision="0"
              style="width: 100%"
              placeholder="请输入数量"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="介绍" prop="text">
        <el-input 
          v-model="drugForm.text" 
          type="textarea"
          :rows="3"
          placeholder="请输入药品介绍"
          maxlength="500"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button + .el-button {
  margin-left: 10px;
}

.el-table {
  margin-top: 20px;
}

.el-form-item:last-child {
  margin-right: 0;
  margin-bottom: 0;
}
</style>